<template>
  <div class="edit-temp">
    <el-form :model="form" :rules="rules" label-position="top" ref="formRef">
      <el-form-item label="模版名称" prop="name">
        <el-input
          class="width-full"
          v-model.trim="form.name"
          maxlength="20"
          show-word-limit
          placeholder="请输入模版名称，不超过20个字符"
        ></el-input>
      </el-form-item>
      <el-form-item label="模版描述" prop="description">
        <el-input
          type="textarea"
          class="width-full"
          v-model.trim="form.description"
          maxlength="200"
          show-word-limit
          rows="3"
          placeholder="请输入模版描述，不超过200个字符"
        ></el-input>
      </el-form-item>
      <el-form-item label="应用场景" prop="scenes">
        <el-select v-model="form.scenes" multiple placeholder="请选择应用场景" class="width-full" disabled>
          <el-option label="呼叫中心" value="callCenter"> </el-option>
          <el-option label="在线-留言" value="imLeaveMsg"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="模版状态" prop="status" class="status-right">
        <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>
    <div class="title">模版字段设置</div>
    <div class="add-btn" @click="addField">
      <i class="el-icon-plus"></i>
      添加字段
    </div>
    <el-table :data="tableData" size="mini" style="width: 100%">
      <el-table-column type="index" width="50"> </el-table-column>
      <el-table-column prop="name" label="字段名称"> </el-table-column>
      <el-table-column prop="type" label="字段类型">
      </el-table-column>
      <el-table-column prop="required" label="是否必填">
        <template scope="scope"
          ><span>{{ scope.row.required ? '是' : '否' }}</span></template
        >
      </el-table-column>
      <el-table-column prop="status" label="当前状态">
        <template scope="scope"
          ><el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="changeStatus(scope.row, scope.$index)"
            inline-prompt
        /></template>
      </el-table-column>
      <el-table-column prop="sort" label="排序">
        <template scope="scope"
          ><span
            v-if="scope.$index !== 0"
            class="iconfont icon-zhiding main-color"
            @click="toTop(scope.$index, scope.row)"
          ></span>
          <span
            v-if="scope.$index !== 0"
            class="iconfont icon-shangsheng main-color"
            @click="moveUp(scope.$index, scope.row)"
          ></span>
          <span
            v-if="scope.$index !== tableData.length - 1"
            class="iconfont icon-xiajiang main-color"
            @click="moveDown(scope.$index, scope.row)"
          ></span
        ></template>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <span class="edit-btn main-color" @click.stop="editField(scope.row)">{{ $t('public.edit') }}</span>
          <span class="del-btn" v-if="!scope.row.builtin" @click.stop="delField(scope.row, scope.$index)">{{
            $t('public.delete')
          }}</span>
        </template>
      </el-table-column>
    </el-table>
    <addTempField
      ref="addTempField"
      @onSaveData="updatTable"
      :tableData="tableData"
      :globalFields="globalFields"
    ></addTempField>
  </div>
</template>
<script>
import addTempField from './addTempField.vue'
import { typeAllMap } from '../globalField/utils/utils.js'
export default {
  name: 'editTemp',
  data() {
    return {
      typeAllMap: typeAllMap,
      tableData: [],
      form: {
        status: 1,
        name: '',
        description: '',
        scenes: ['imLeaveMsg'],
        fields: []
      },
      rules: {
        name: [{ required: true, message: '请输入模版名称', trigger: 'blur' }]
      }
    }
  },
  components: {
    addTempField
  },
  props: {
    globalFieldsObj: {
      type: Object,
      default: () => {}
    },
    globalFields: {
      type: Array,
      default: () => []
    }
  },
  methods: {
    changeStatus(row, index) {
      this.$confirm(`请确认是否${row.status ? '启用' : '停用'}该字段？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.tableData[index].status = row.status
        })
        .catch(() => {
          this.tableData[index].status = row.status ? 0 : 1
        })
    },
    delField(row, idx) {
      this.$confirm(`${row.name}字段删除后将无法恢复，点击确定删除字段`, '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData.splice(idx, 1)
      })
    },
    editField(row) {
      this.$refs.addTempField.openDialog('edit', row)
    },
    moveUp(index, row) {
      // 上移
      this.tableData[index] = this.tableData.splice(index - 1, 1, row)[0]
    },
    moveDown(index, row) {
      // 下移
      this.tableData[index] = this.tableData.splice(index + 1, 1, row)[0]
    },
    toTop(index, row) {
      // 置顶
      this.tableData.splice(index, 1)
      this.tableData.unshift(row)
    },
    getFields(field) {
      const data = this.globalFieldsObj[field]
      if (data) {
        return {
          name: data.name || '',
          type: typeAllMap[data.type] || ''
        }
      }
      return {}
    },
    updatTable(data, type) {
      const fieldObj = this.getFields(data.field)
      const obj = {
        ...data,
        name: fieldObj.name,
        type: fieldObj.type
      }
      if (type === 'add') {
        // 新建的字段
        this.tableData.push(obj)
      } else {
        // 编辑字段
        this.tableData.forEach((item, idx) => {
          if (item.field === data.field) {
            this.$set(this.tableData, idx, obj)
          }
        })
      }
    },
    open(type, row) {
      if (type == 'edit') {
        this.form = row
        this.tableData = row.fields.map(item => {
          const fieldObj = this.getFields(item.field)
          item.name = fieldObj.name || ''
          item.type = fieldObj.type
          return item
        })
      } else {
        this.tableData = []
        this.form = {
          status: 1,
          name: '',
          description: '',
          scenes: ['imLeaveMsg'],
          fields: []
        }
      }
      this.$refs['formRef'].clearValidate()
    },
    save() {
      if (!this.tableData.filter((item) => item.status).length) {
        this.$message.error('模版字段至少有一个启用的')
        return
      }
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const { status, name, description, scenes } = this.form
          let data = { status, name, description, scenes, fields: this.tableData }
          if (this.form._id) {
            data._id = this.form._id
          }
          this.$store.dispatch(data._id ? 'updateDynamicform' : 'createDynamicform', data).then((resp) => {
            if (resp && resp.success) {
              this.$message.success(`${data._id ? '编辑' : '添加'}模版成功`)
              this.$emit('updateSuccess')
            }
          })
        }
      })
    },
    addField() {
      this.$refs.addTempField.openDialog('add', {})
    }
  }
}
</script>

<style lang="stylus" scoped>
.iconfont {
  font-size: 14px;
  font-weight: normal;
}
.main-color
  color #459ae9
  cursor pointer
.width-full
  width: 100%
.edit-temp
  .return
    .icon
      cursor pointer
      .MC_icon-fangxiang-zuo-xian
        color rgba(0, 0, 0, 0.6)
        font-size 18px
        position relative
        top 2px
    .line
      color #DCDCDC
      margin 0 8px
    .tip
      color rgba(0, 0, 0, 0.6)
  .title
    height 36px
    padding 0 20px
    line-height 36px
    box-sizing border-box
    background rgba(30, 99, 245, 0.1)
    border-radius 4px
    font-size 14px
    color rgba(0, 0, 0, 0.88)
    font-weight 500
    margin 16px 0
  .status-right
    display flex
    align-items center
    :deep(.el-form-item__label)
      margin-bottom 0
  .add-btn
    float right
    color #459ae9
    cursor pointer
    margin-bottom 16px
  .btn
    color #459ae9
    cursor pointer
    margin-right 16px
    &:last-child
      margin-right 0px
  .operate-btn
    background #fff
    z-index 3
    position fixed
    bottom 0
    left 240px
    right 0
    height 60px
    padding 12px 24px
    box-sizing border-box
    text-align right
    border-top 1px solid #f2f2f2
  .table
    .el-icon-plus
      color #459ae9
      margin-right 10px
      &:last-child
        margin-right 0
.del-btn
  cursor pointer
  color: #ff6b6b
  margin-left 10px
.MC_iconfont
  color #459ae9
  margin-right 10px
  cursor pointer
  &:last-child
    margin-right 0
</style>
